package server.util;

import base.BaseValue;
import com.alibaba.fastjson.JSON;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.converters.*;
import server.util.InfoUtils.Info;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import java.io.File;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class MyUtils {
    public static <T> T convertRequest2Bean(HttpServletRequest request, Class<T> clazzBean,
                                            String fileUploadPath, String filePrefix) {
        T tb = null;

        ConvertUtils.register(new DateTimeConverter(), Date.class);

        ConvertUtils.register(new ByteConverter(), Byte.class);
        ConvertUtils.register(new LongConverter(), Long.class);
        ConvertUtils.register(new FloatConverter(), Float.class);
        ConvertUtils.register(new ShortConverter(), Short.class);
        ConvertUtils.register(new IntegerConverter(), Integer.class);
        ConvertUtils.register(new DoubleConverter(), Double.class);
        ConvertUtils.register(new BigDecimalConverter(), BigDecimal.class);
        try {
            tb = clazzBean.newInstance();

            Enumeration<String> strPNames = request.getParameterNames();
            if (strPNames != null) {
                while (strPNames.hasMoreElements()) {
                    String pName = strPNames.nextElement();
                    String pVale = request.getParameter(pName);
                    System.out.println(pName + ":  " + pVale);
                    BeanUtils.setProperty(tb, pName, pVale);
                }
            }


            if (request.getContentType() != null && request.getContentType().split(";")[0].equals("multipart/form-data")) {
                Collection<Part> parts = request.getParts();
                //储存pic网址的数组
                ArrayList<String> pics = new ArrayList<>();
                for (Part part : parts) {
                    String pName = part.getName();
                    String pContentType = part.getContentType();
                    System.out.println(pContentType);

                    if (pContentType != null && !pContentType.startsWith("application/json") && part.getSize() > 0) {

                        String strFileOldName = part.getSubmittedFileName();
                        if (strFileOldName == null) {
                            continue;
                        }
                        //String realPath = request.getServletContext().getRealPath("/");

                        File f = new File(fileUploadPath);
                        if (!f.exists()) {
                            f.mkdirs();
                        }
                        System.out.println("打印上传目录：" + f.getAbsolutePath());

                        String strFileType = strFileOldName.substring(strFileOldName.lastIndexOf('.'));
                        String strUploadFileName = filePrefix + "_" + UUID.randomUUID() + strFileType;
                        part.write(fileUploadPath + strUploadFileName);
                        pics.add(BaseValue.getPicLoad + strUploadFileName);
                    }
                }
                //将pics数组转化为json储存在对象的pic属性中
                if (filePrefix.startsWith("user") && pics.size() == 1) {
                    BeanUtils.setProperty(tb, "pic", pics.get(0));
                } else {
                    BeanUtils.setProperty(tb, "pic", toJson(pics));
                }
            }
        } catch (Exception e) {
            System.out.println("获取实体类异常" + e.getMessage());
            e.printStackTrace();
        }
        return tb;
    }

    public static <T> T convertRequest2Bean(HttpServletRequest request, Class<T> clazzBean) {
        T tb = null;

        ConvertUtils.register(new DateTimeConverter(), Date.class);

        ConvertUtils.register(new ByteConverter(), Byte.class);
        ConvertUtils.register(new LongConverter(), Long.class);
        ConvertUtils.register(new FloatConverter(), Float.class);
        ConvertUtils.register(new ShortConverter(), Short.class);
        ConvertUtils.register(new IntegerConverter(), Integer.class);
        ConvertUtils.register(new DoubleConverter(), Double.class);
        ConvertUtils.register(new BigDecimalConverter(), BigDecimal.class);
        try {
            tb = clazzBean.newInstance();

            Enumeration<String> strPNames = request.getParameterNames();
            if (strPNames != null) {
                while (strPNames.hasMoreElements()) {
                    String pName = strPNames.nextElement();
                    String pVale = request.getParameter(pName);
                    System.out.println(pName + ":  " + pVale);
                    BeanUtils.setProperty(tb, pName, pVale);
                }
            }
        } catch (Exception e) {
            System.out.println("获取实体类异常" + e.getMessage());
            e.printStackTrace();
        }
        return tb;
    }

    public static Integer convertString2Integer(String strVal) {
        if (strVal == null || strVal.equals("")) {
            return null;
        } else {
            return Integer.valueOf(strVal);
        }
    }


    public static <T> T getNewInstance(Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (Exception e) {
            System.out.println("公用方法：实例化对象异常：" + e.getMessage());
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 将日期类型转为指定格式的字符串
     *
     * @param date       被转换的日期类型
     * @param strPattern 日期格式串
     * @return 转换之后的字符串
     */
    public static String convertDate2String(Date date, String strPattern) {
        // 如果时间对象为null则，返回当前时间
        if (date == null) {
            date = new Date();
        }
        // 如果格式串为空则使用默认格式
        if (strPattern == null || strPattern.equals("")) {
            // 默认格式串
            strPattern = "yyyy-MM-dd HH:mm:ss";
        }
        // 创建一个日期对象转换类
        SimpleDateFormat sdf = new SimpleDateFormat(strPattern);
        // 返回转换之后的字符串
        return sdf.format(date);
    }


    /**
     * 将指定格式的字符串转换为日期类型 (strPattern的格式表示是strDate的格式)
     *
     * @param strDate    日期字符串
     * @param strPattern 日期字符串的格式
     * @return 转换之后的日期对象
     */
    public static Date convertString2Date(String strDate, String strPattern) {
        // 如果时间对象为null则，返回当前时间


        if (strDate == null || strDate.equals("")) {
            return new Date();
        }
        // 如果格式串为空则使用默认格式
        if (strPattern == null || strPattern.equals("")) {
            // 默认格式串
            strPattern = "yyyy-MM-dd HH:mm:ss";
        }
        // 创建一个日期对象转换类
        SimpleDateFormat sdf = new SimpleDateFormat(strPattern);
        // 返回转换之后的时间对象
        Date date = null;
        try {
            date = sdf.parse(strDate);
        } catch (ParseException e) {
            // 公用方法：字符串转换日期对象异常：
            //logRootLogger.error("公用方法-字符串转换日期对象异常：" + e.getMessage());
            e.printStackTrace();
        }
        return date;
    }

    public static Double formatDouble(Double d) {
        //保留小数点后两位数
        return (double) Math.round(d * 100) / 100;
    }

    public static boolean NOTNULL(String str) {
        if (str != null && !"".equals(str.trim())) {
            return true;
        } else {
            return false;
        }
    }

    public static boolean NOTNULL(Object... strs) {
        for (Object str : strs) {
            if (str == null || !NOTNULL(str.toString())) {
                return false;
            }
        }
        return true;
    }


    //将对象转化为json
    public static String toJson(Object object) {
        return toJson(object, 1);
    }

    public static String toJson(Object object, int flag) {
        final String flag1 = "yyyy-MM-dd";
        final String flag2 = "yyyy-MM-dd HH:mm";
        String endFlag = null;

        switch (flag) {
            case 1:
                endFlag = flag1;
                break;
            case 2:
                endFlag = flag2;
                break;
        }
        return JSON.toJSONStringWithDateFormat(object, endFlag);
    }

    //将json转化为对象
    public static <T> T fromJson(String json, Class<T> clazz) {
        T tb = null;
        try {
            tb = JSON.parseObject(json, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tb;
    }

    //将json转化为Info对象
    public static Info getInfoFromJson(String json) {
        return fromJson(json, Info.class);
    }

    //将json中data对应的dataJson转化为对象
    public static <T> T getDataFromJson(String json, Class<T> clazz) {
        String dataJson = JSON.parseObject(json).getString("data");
        return fromJson(dataJson, clazz);
    }

    //将json转化为Integer数组，例如"[5,7,8]"
    public static List<Integer> getIntArray(String arrayJson) {
        List<Integer> array = JSON.parseArray(arrayJson, Integer.class);
        return array;
    }

    //将json转化为String数组，例如"["hebf","egh2u"]"
    public static List<String> getStringArray(String arrayJson) {
        List<String> array = JSON.parseArray(arrayJson, String.class);
        return array;
    }

}
